package com.example.hrmsaas.system.realm;

import com.example.hrmsaas.system.entity.User;
import com.example.hrmsaas.system.service.IUserService;
import com.example.hrmsaas.system.utils.ActiverUser;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;

public class UserRealm extends AuthorizingRealm {
    @Autowired
    @Lazy
    IUserService userService;

    public String getName()
    {
        return this.getClass().getSimpleName();
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        User user = this.userService.getUserObjectByUserName(authenticationToken.getPrincipal().toString());
        //如果用户不存在
        if (user != null) {
            //创建ActiverUser
            ActiverUser activerUser = new ActiverUser();
            activerUser.setUser(user);
            //生成盐
            ByteSource credentialsSalt =  ByteSource.Util.bytes(user.getSalt());
            SimpleAuthenticationInfo info=new SimpleAuthenticationInfo(activerUser,user.getPwd(),credentialsSalt,this.getName()) ;
            return info;
        }
        return null;
    }

    /**
     * 授权
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }


}
